import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isBoolean from "lodash/isBoolean";
var _excluded = ["_status"],
    _excluded2 = ["_status"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _dec14, _class;

/**
 * 角色分配卡片
 * RoleAssignCardsEditModal
 * 使用 didUpdate 判断需不需要从新加载卡片
 * 重新加载卡片的条件是 visible 为 true, 且有角色信息
 * @date 2019-01-25
 */
import React from 'react';
import { Bind } from 'lodash-decorators';
import { Modal, InputNumber, Form, Table, Row, Col } from 'antd'; // import uuid from 'uuid/v4';

import { operatorRender } from 'utils/renderer';
import EditTable from 'components/EditTable';
import Checkbox from 'components/Checkbox';
import { Button as ButtonPermission } from 'components/Permission';
import { createPagination, delItemsToPagination, delItemToPagination, getEditTableData, tableScrollWidth } from 'utils/utils';
import { SEARCH_FORM_ITEM_LAYOUT } from 'utils/constants';
import intl from 'utils/intl';
import notification from 'utils/notification';
import ModalFilter from "./ModalFilter";
var CARD_MAX_HEIGHT = 200;
var patchInputStyle = {
  width: '100%'
};

function getRefFieldsValue(ref) {
  if (ref.current) {
    return ref.current.props.form.getFieldsValue();
  }

  return {};
}
/**
 * @ReactProps {!Function} onFetchRoleCards - 查询已经分配的卡片
 */


var RoleAssignCardsEditModal = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec13 = Bind(), _dec14 = Bind(), (_class = /*#__PURE__*/function (_React$Component) {
  _inherits(RoleAssignCardsEditModal, _React$Component);

  var _super = _createSuper(RoleAssignCardsEditModal);

  function RoleAssignCardsEditModal(props) {
    var _this;

    _classCallCheck(this, RoleAssignCardsEditModal);

    _this = _super.call(this, props);
    _this.columns = [{
      title: intl.get('ciam.roleManagement.model.tenantAssignCards.cardCode').d('卡片代码'),
      dataIndex: 'code',
      width: 180
    }, {
      title: intl.get('ciam.roleManagement.model.tenantAssignCards.cardName').d('卡片名称'),
      dataIndex: 'name'
    }, {
      title: intl.get('ciam.roleManagement.model.tenantAssignCards.cardType').d('卡片类别'),
      dataIndex: 'catalogMeaning',
      width: 100
    }, {
      title: intl.get('ciam.roleManagement.model.tenantAssignCards.cardH').d('高度'),
      dataIndex: 'h',
      width: 80,
      align: 'right'
    }, {
      title: intl.get('ciam.roleManagement.model.tenantAssignCards.cardW').d('长度'),
      dataIndex: 'w',
      width: 80
    }, {
      title: intl.get('ciam.roleManagement.model.tenantAssignCards.cardX').d('位置X'),
      dataIndex: 'x',
      width: 120,
      render: function render(x, record) {
        if (record._status) {
          var form = record.$form;
          var formOptions = {
            rules: [{
              required: true,
              message: intl.get('cpaas.common.validation.notNull', {
                name: intl.get('ciam.roleManagement.model.tenantAssignCards.cardX').d('位置X')
              })
            }]
          };
          formOptions.initialValue = record._status === 'update' ? x : 0;
          return /*#__PURE__*/React.createElement(Form.Item, null, form.getFieldDecorator('x', formOptions)( /*#__PURE__*/React.createElement(InputNumber, {
            min: 0,
            max: CARD_MAX_HEIGHT,
            precision: 0,
            step: 1,
            style: patchInputStyle
          })));
        } else {
          return x;
        }
      }
    }, {
      title: intl.get('ciam.roleManagement.model.tenantAssignCards.cardY').d('位置Y'),
      dataIndex: 'y',
      width: 120,
      align: 'right',
      render: function render(y, record) {
        if (record._status) {
          var form = record.$form;
          var formOptions = {
            rules: [{
              required: true,
              message: intl.get('cpaas.common.validation.notNull', {
                name: intl.get('ciam.roleManagement.model.tenantAssignCards.cardY').d('位置Y')
              })
            }]
          };
          formOptions.initialValue = record._status === 'update' ? y : 0;
          return /*#__PURE__*/React.createElement(Form.Item, null, form.getFieldDecorator('y', formOptions)( /*#__PURE__*/React.createElement(InputNumber, {
            min: 0,
            max: CARD_MAX_HEIGHT,
            precision: 0,
            step: 1,
            style: patchInputStyle
          })));
        } else {
          return y;
        }
      }
    }, {
      title: intl.get('ciam.roleManagement.model.tenantAssignCards.cardInit').d('初始化'),
      dataIndex: 'defaultDisplayFlag',
      width: 80,
      render: function render(defaultDisplayFlag, record) {
        if (record._status) {
          var form = record.$form;
          var formOptions = {};

          if (record._status === 'update') {
            formOptions.initialValue = defaultDisplayFlag;
          } else {
            formOptions.initialValue = 0;
          }

          return form.getFieldDecorator('defaultDisplayFlag', formOptions)( /*#__PURE__*/React.createElement(Checkbox, null));
        } else {
          return /*#__PURE__*/React.createElement(Checkbox, {
            checked: defaultDisplayFlag === 1,
            disabled: true
          });
        }
      }
    }, {
      title: intl.get('cpaas.common.button.action').d('操作'),
      width: 85,
      fixed: 'right',
      render: function render(_, record) {
        var path = _this.props.path;
        var operators = [];

        if (record._status === 'create') {
          operators.push({
            key: 'clean',
            ele: /*#__PURE__*/React.createElement(ButtonPermission, {
              type: "text",
              permissionList: [{
                code: "".concat(path, ".button.cleanCardCreate"),
                type: 'button',
                meaning: '角色管理-清除卡片分配新增'
              }],
              key: "action-create",
              onClick: _this.handleLineClean.bind(undefined, record)
            }, intl.get('cpaas.common.button.clean').d('清除')),
            len: 2,
            title: intl.get('cpaas.common.button.clean').d('清除')
          });
        } else if (record._status === 'update') {
          operators.push({
            key: 'cancel',
            ele: /*#__PURE__*/React.createElement("a", {
              key: "action-cancel",
              onClick: _this.handleLineEditCancel.bind(undefined, record)
            }, intl.get('cpaas.common.button.cancel').d('取消')),
            len: 2,
            title: intl.get('cpaas.common.button.cancel').d('取消')
          });
        } else {
          operators.push({
            key: 'edit',
            ele: /*#__PURE__*/React.createElement(ButtonPermission, {
              type: "text",
              permissionList: [{
                code: "".concat(path, ".button.editCardAssign"),
                type: 'button',
                meaning: '角色管理-编辑卡片分配'
              }],
              key: "action-edit",
              onClick: _this.handleLineEdit.bind(undefined, record)
            }, intl.get('cpaas.common.button.edit').d('编辑')),
            len: 2,
            title: intl.get('cpaas.common.button.edit').d('编辑')
          });
        }

        return operatorRender(operators);
      }
    }].filter(function (column) {
      return !_isBoolean(column);
    });
    _this.oneSearchFormRef = React.createRef();
    _this.state = {
      rowSelection: {
        selectedRowKeys: [],
        selectedRows: [],
        onChange: _this.handleRowSelectionChange
      },
      dataSource: [],
      pagination: false,
      addModalVisible: false,
      selectedAddRows: []
    };
    return _this;
  }

  _createClass(RoleAssignCardsEditModal, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var role = prevProps.role;
      var _this$props = this.props,
          visible = _this$props.visible,
          nextRole = _this$props.role;

      if (visible) {
        if (nextRole && role !== nextRole) {
          // 两个角色不相同 且有下一个角色
          this.fetchRoleCards();
        }
      }
    }
  }, {
    key: "handleSelectAddRows",
    value: function handleSelectAddRows(_, selectedAddRows) {
      this.setState({
        selectedAddRows: selectedAddRows
      });
    }
  }, {
    key: "handleAddCancel",
    value: function handleAddCancel() {
      this.setState({
        selectedAddRows: [],
        addModalVisible: false
      });
    }
  }, {
    key: "handleAddOk",
    value: function handleAddOk() {
      var _this2 = this;

      var selectedAddRows = this.state.selectedAddRows;
      var _this$props2 = this.props,
          role = _this$props2.role,
          onAdd = _this$props2.onAdd;
      onAdd(selectedAddRows.map(function (item) {
        return _objectSpread(_objectSpread({}, item), {}, {
          roleId: role.id,
          x: 0,
          y: 0,
          defaultDisplayFlag: 0
        });
      })).then(function () {
        _this2.setState({
          addModalVisible: false,
          selectedAddRows: []
        });

        _this2.fetchRoleCards();
      });
    }
  }, {
    key: "cardPageChange",
    value: function cardPageChange() {
      var pagination = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var fieldsValue = getRefFieldsValue(this.oneSearchFormRef);
      var cardTableChange = this.props.cardTableChange;
      cardTableChange(pagination, fieldsValue);
    }
  }, {
    key: "handleOneSearchFormSearch",
    value: function handleOneSearchFormSearch() {
      var onFormSearch = this.props.onFormSearch;
      var fieldsValue = getRefFieldsValue(this.oneSearchFormRef);
      onFormSearch(fieldsValue);
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
          visible = _this$props3.visible,
          role = _this$props3.role,
          loading = _this$props3.loading,
          path = _this$props3.path,
          _this$props3$cardList = _this$props3.cardList,
          cardList = _this$props3$cardList === void 0 ? [] : _this$props3$cardList,
          _this$props3$cardList2 = _this$props3.cardListPagination,
          cardListPagination = _this$props3$cardList2 === void 0 ? {} : _this$props3$cardList2,
          queryRoleCardLoading = _this$props3.queryRoleCardLoading;
      var _this$state = this.state,
          dataSource = _this$state.dataSource,
          pagination = _this$state.pagination,
          rowSelection = _this$state.rowSelection,
          addModalVisible = _this$state.addModalVisible,
          _this$state$selectedA = _this$state.selectedAddRows,
          selectedAddRows = _this$state$selectedA === void 0 ? [] : _this$state$selectedA;
      var rowAddSelection = {
        selectedRowKeys: selectedAddRows.map(function (n) {
          return n.cardId;
        }),
        onChange: this.handleSelectAddRows
      };
      var addColumns = [{
        title: intl.get('ciam.roleManagement.model.roleManagement.cardCode').d('卡片代码'),
        dataIndex: 'code'
      }, {
        title: intl.get('ciam.roleManagement.model.roleManagement.cardName').d('卡片名称'),
        dataIndex: 'name'
      }, {
        title: intl.get('ciam.roleManagement.model.roleManagement.catalogMeaning').d('卡片类型'),
        dataIndex: 'catalogMeaning'
      }];
      return /*#__PURE__*/React.createElement(Modal, {
        title: intl.get('ciam.roleManagement.view.title.assignCards').d('工作台配置'),
        width: "1000px",
        wrapClassName: "ant-modal-sidebar-right",
        transitionName: "move-right",
        visible: visible,
        onOk: this.handleModalOkBtnClick,
        onCancel: this.handleModalCancelBtnClick,
        confirmLoading: loading.saveRoleCards,
        cancelText: intl.get('cpaas.common.button.close').d('关闭')
      }, /*#__PURE__*/React.createElement("div", {
        className: "table-list-operator"
      }, /*#__PURE__*/React.createElement(Form, null, /*#__PURE__*/React.createElement(Row, {
        type: "flex",
        gutter: 24,
        align: "bottom"
      }, /*#__PURE__*/React.createElement(Col, {
        span: 8
      }, /*#__PURE__*/React.createElement(Form.Item, Object.assign({}, SEARCH_FORM_ITEM_LAYOUT, {
        label: intl.get('ciam.roleManagement.model.roleManagement.name').d('角色名称')
      }), role.name)), /*#__PURE__*/React.createElement(Col, {
        span: 8
      }, /*#__PURE__*/React.createElement(Form.Item, Object.assign({}, SEARCH_FORM_ITEM_LAYOUT, {
        label: intl.get('ciam.roleManagement.model.roleManagement.code').d('角色编码')
      }), role.code))))), /*#__PURE__*/React.createElement("div", {
        className: "table-list-operator",
        style: {
          textAlign: 'right'
        }
      }, /*#__PURE__*/React.createElement(ButtonPermission, {
        permissionList: [{
          code: "".concat(path, ".button.deleteCardAssign"),
          type: 'button',
          meaning: '角色管理-删除卡片分配'
        }],
        key: "remove",
        disabled: rowSelection.selectedRowKeys.length === 0,
        onClick: this.handleRemoveBtnClick,
        loading: loading.removeRoleCards
      }, intl.get('cpaas.common.button.delete').d('删除')), /*#__PURE__*/React.createElement(ButtonPermission, {
        permissionList: [{
          code: "".concat(path, ".button.addCardAssign"),
          type: 'button',
          meaning: '角色管理-新建角色分配'
        }],
        type: "primary",
        key: "add",
        onClick: this.handleAddBtnClick
      }, intl.get('cpaas.common.button.add').d('新增'))), /*#__PURE__*/React.createElement(EditTable, {
        bordered: true,
        rowKey: "id",
        columns: this.columns,
        scroll: {
          x: tableScrollWidth(this.columns)
        },
        onChange: this.handleTableChange,
        pagination: pagination,
        dataSource: dataSource,
        rowSelection: rowSelection,
        loading: loading.fetchRoleCards
      }), /*#__PURE__*/React.createElement(Modal, {
        destroyOnClose: true,
        visible: addModalVisible,
        title: intl.get('ciam.roleManagement.view.title.choseCards').d('选择卡片'),
        onCancel: this.handleAddCancel,
        onOk: this.handleAddOk,
        width: 800
      }, /*#__PURE__*/React.createElement(ModalFilter, {
        wrappedComponentRef: this.oneSearchFormRef,
        onSearch: this.handleOneSearchFormSearch
      }), /*#__PURE__*/React.createElement(Table, {
        rowKey: "cardId",
        bordered: true,
        loading: queryRoleCardLoading,
        dataSource: cardList,
        rowSelection: rowAddSelection,
        pagination: cardListPagination,
        columns: addColumns,
        onChange: this.cardPageChange
      })));
    }
    /**
     * 查询角色拥有的卡片
     */

  }, {
    key: "fetchRoleCards",
    value: function fetchRoleCards() {
      var _this3 = this;

      var pagination = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var _this$props4 = this.props,
          onFetchRoleCards = _this$props4.onFetchRoleCards,
          role = _this$props4.role;

      var payload = _objectSpread({
        roleId: role.id
      }, pagination);

      if (role.id !== undefined) {
        // 有角色 才能查询
        onFetchRoleCards(payload).then(function (res) {
          if (res) {
            _this3.setState({
              dataSource: res.content,
              pagination: createPagination(res)
            });
          }
        });
      }
    } // Modal 相关

  }, {
    key: "handleModalOkBtnClick",
    value: function handleModalOkBtnClick() {
      var _this$props5 = this.props,
          onCancel = _this$props5.onCancel,
          onOk = _this$props5.onOk,
          role = _this$props5.role;
      var dataSource = this.state.dataSource;
      var updateOrCreateData = dataSource.filter(function (r) {
        return r._status;
      });

      if (updateOrCreateData.length > 0) {
        // 有需要更新的数据
        var validationData = getEditTableData(updateOrCreateData, ['_status', 'id']);

        if (validationData.length === updateOrCreateData.length) {
          onOk(validationData.map(function (r) {
            var _status = r._status,
                restR = _objectWithoutProperties(r, _excluded);

            return _objectSpread(_objectSpread({}, restR), {}, {
              roleId: role.id
            });
          }));
        }
      } else {
        onCancel();
      }
    }
  }, {
    key: "handleModalCancelBtnClick",
    value: function handleModalCancelBtnClick() {
      var onCancel = this.props.onCancel;
      onCancel();
    } // 头按钮相关

  }, {
    key: "handleAddBtnClick",
    value: function handleAddBtnClick() {
      var _this$props6 = this.props,
          onAddCard = _this$props6.onAddCard,
          id = _this$props6.role.id; // const { dataSource, pagination } = this.state;

      onAddCard({
        roleId: id
      });
      this.setState({
        // 新增卡片 x,y 默认为0
        addModalVisible: true // dataSource: [{ id: uuid(), _status: 'create', x: 0, y: 0 }, ...dataSource],
        // pagination: addItemToPagination(dataSource.length, pagination),

      });
    }
  }, {
    key: "handleRemoveBtnClick",
    value: function handleRemoveBtnClick() {
      var _this4 = this;

      var _this$state2 = this.state,
          selectedRows = _this$state2.rowSelection.selectedRows,
          dataSource = _this$state2.dataSource,
          pagination = _this$state2.pagination;
      var addRows = [];
      var oriRows = [];
      selectedRows.forEach(function (record) {
        if (record._status === 'create') {
          addRows.push(record);
        } else {
          oriRows.push(record);
        }
      });

      if (oriRows.length > 0) {
        var onRemoveRoleCards = this.props.onRemoveRoleCards;
        onRemoveRoleCards(oriRows).then(function (res) {
          if (res) {
            notification.success(); // 删除成功

            _this4.setState({
              dataSource: dataSource.filter(function (r) {
                return !selectedRows.some(function (addR) {
                  return addR.id === r.id;
                });
              }),
              pagination: delItemsToPagination(selectedRows.length, dataSource.length, pagination),
              rowSelection: {
                selectedRowKeys: [],
                selectedRows: [],
                onChange: _this4.handleRowSelectionChange
              }
            });
          }
        });
      } else {
        notification.success();
        this.setState({
          dataSource: dataSource.filter(function (r) {
            return !addRows.some(function (addR) {
              return addR.id === r.id;
            });
          }),
          pagination: delItemsToPagination(addRows.length, dataSource.length, pagination),
          rowSelection: {
            selectedRowKeys: [],
            selectedRows: [],
            onChange: this.handleRowSelectionChange
          }
        });
      }
    } // Table 相关

  }, {
    key: "handleTableChange",
    value: function handleTableChange(page, filter, sort) {
      this.fetchRoleCards({
        page: page,
        sort: sort
      });
    }
  }, {
    key: "handleRowSelectionChange",
    value: function handleRowSelectionChange(_, selectedRows) {
      this.setState({
        rowSelection: {
          selectedRows: selectedRows,
          onChange: this.handleRowSelectionChange,
          selectedRowKeys: selectedRows.map(function (r) {
            return r.id;
          })
        }
      });
    }
  }, {
    key: "handleLineEdit",
    value: function handleLineEdit(record) {
      var dataSource = this.state.dataSource;
      this.setState({
        dataSource: dataSource.map(function (r) {
          if (r.id === record.id) {
            return _objectSpread(_objectSpread({}, r), {}, {
              _status: 'update'
            });
          } else {
            return r;
          }
        })
      });
    }
  }, {
    key: "handleLineEditCancel",
    value: function handleLineEditCancel(record) {
      var dataSource = this.state.dataSource;
      this.setState({
        dataSource: dataSource.map(function (r) {
          if (r.id === record.id) {
            var _status = r._status,
                oriRecord = _objectWithoutProperties(r, _excluded2);

            return oriRecord;
          } else {
            return r;
          }
        })
      });
    }
  }, {
    key: "handleLineClean",
    value: function handleLineClean(record) {
      var _this$state3 = this.state,
          dataSource = _this$state3.dataSource,
          rowSelection = _this$state3.rowSelection,
          pagination = _this$state3.pagination;
      var nextSelectedRows = rowSelection.selectedRows.filter(function (r) {
        return r.id !== record.id;
      });
      this.setState({
        dataSource: dataSource.filter(function (r) {
          return r.id !== record.id;
        }),
        pagination: delItemToPagination(dataSource.length, pagination),
        rowSelection: _objectSpread(_objectSpread({}, rowSelection), {}, {
          selectedRows: nextSelectedRows,
          selectedRowKeys: nextSelectedRows.map(function (r) {
            return r.id;
          })
        })
      });
    }
  }]);

  return RoleAssignCardsEditModal;
}(React.Component), (_applyDecoratedDescriptor(_class.prototype, "handleSelectAddRows", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "handleSelectAddRows"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleAddCancel", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "handleAddCancel"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleAddOk", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "handleAddOk"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "cardPageChange", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "cardPageChange"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleOneSearchFormSearch", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "handleOneSearchFormSearch"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleModalOkBtnClick", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "handleModalOkBtnClick"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleModalCancelBtnClick", [_dec7], Object.getOwnPropertyDescriptor(_class.prototype, "handleModalCancelBtnClick"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleAddBtnClick", [_dec8], Object.getOwnPropertyDescriptor(_class.prototype, "handleAddBtnClick"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleRemoveBtnClick", [_dec9], Object.getOwnPropertyDescriptor(_class.prototype, "handleRemoveBtnClick"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleTableChange", [_dec10], Object.getOwnPropertyDescriptor(_class.prototype, "handleTableChange"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleRowSelectionChange", [_dec11], Object.getOwnPropertyDescriptor(_class.prototype, "handleRowSelectionChange"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleLineEdit", [_dec12], Object.getOwnPropertyDescriptor(_class.prototype, "handleLineEdit"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleLineEditCancel", [_dec13], Object.getOwnPropertyDescriptor(_class.prototype, "handleLineEditCancel"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleLineClean", [_dec14], Object.getOwnPropertyDescriptor(_class.prototype, "handleLineClean"), _class.prototype)), _class));
export { RoleAssignCardsEditModal as default };